//index.js
//获取应用实例//获取应用实例
var QQMapWX = require('../../utils/qqmap-wx-jssdk.js')  //引入获得地址的js文件
var qqmapsdk;
const app = getApp()

Page({
  data: {
    title:"2020年世界低碳骑行日骑行公益大型活动",
    subTitle:"保护地球从你我做起！",
    isempower:false,//判断用户是否授权
    todaystep:0,//今天的步数
    nick_name:"",
    head_img:"",
    dontNotice:true,
    invitecode:"",
    mobile: "",
    name:"",
    runData: [],//步数数据
    activity_notice: "《纽约客》撰稿人凯瑟琳·舒尔茨做过两次盘点，总结她“一年间从书中学到的最佳事实”。我觉得可以再次效仿一下她，摘出这一年我看的书中有趣或者有用的冷知识，大多是在写读书专栏时没有用到的“边角料”。《纽约客》撰稿人凯瑟琳·舒尔茨做过两次盘点，总结她“一年间从书中学到的最佳事实”。我觉得可以再次效仿一下她，摘出这一年我看的书中有趣或者有用的冷知识，大多是在写读书专栏时没有用到的“边角料”。",
    activity_city:[],
    show:false,//是否显示活动须知
    // 地理定位
    latitude: null,//地理定位
    longitude: null,
    address: null,
    province: "",//定位省份
    city: "",//定位城市
  },
  // 显示活动须知
  showPopup() {
    this.setData({ show: true });
  },
  // 隐藏
  onClose() {
    this.setData({ show: false });
  },
  // 活动须知
  hidenotice(){
    this.onClose();
    this.setData({
      dontNotice:false
    })
  },
  //显示授权信息
  showgetUsers() {
    this.setData({ showgetUser: true })
  },
  // 隐藏
  onHide(){
    this.setData({showgetUser:false})
  },
  //事件处理函数
  bindViewTap: function() {
    
  },
  // 是否同意活动须知
  DontNotice(){
    if(this.data.dontNotice===false){
      this.setData({
        dontNotice:true
      })
    }else{
      this.setData({
        dontNotice:false
      })
    }
  },
  // 获取邀请码
  formInvit(e) {
    this.setData({
      invitecode:e.detail.value
    })
  },
  // 获取手机号码
  formMobile(e){
    this.setData({
      mobile:e.detail.value
    })
  },
  // 获取姓名
  formName(e){
    this.setData({
      name:e.detail.value
    })
  },
  // 判断用户是否授权
  regsiter(){
    let that=this
    let userInfo = app.globalData.userInfo
    // console.log(userInfo);
    if (userInfo===null){
      that.showgetUsers();
      that.setData({
        isempower: true
      })
    }else{
      that.setData({
        nick_name: userInfo.nickName,
        head_img: userInfo.avatarUrl
      })
      that.loginin();
    }
  },
  // 授权点击拒绝后提示
  showToast(){
    wx.showToast({
      title: '请点击同意授权后参与活动',
      icon: 'none',
      duration: 5000
    })
  },
  // 开始注册参与活动
  onLogin(){
    //调用小程序API:wx.login获取code和sessionKey；
    var that = this;
    let host = app.globalData.host
    wx.login({
      success: function (resLogin) {
        if (resLogin.code) {
          // 用户注册，参与活动
          wx.request({
            url: host+'/H5/user/register',
            data:{
              code: resLogin.code,
              invitecode: that.data.invitecode,
              nick_name: that.data.nick_name,
              head_img: that.data.head_img,
              province:that.data.province,
              city:that.data.city,
              name:that.data.name,
              mobile:that.data.mobile
            },
            method:"post",
            success(res){
              // console.log(res)
              if (res.data.code === 200) {// 注册成功
                app.globalData.openid=res.data.openid;
              }else if(res.data.code===400){//已注册、注册失败
                that.loginin();
                // console.log('openid:' + app.globalData.openid);//拿不到
              }else{
                console.log(res);
              }
              // 获取微信步数，判断是否大于2000
              that.getstep()
            },
            fail(res){console.log(res)}
          })
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      }
    })
  },
  // 已注册直接登录
  loginin() {
    var that = this;
    let host = app.globalData.host
    wx.login({
      success: function (resLogin) {
        if (resLogin.code) {
          wx.request({
            url: host + '/H5/user/login',
            data: {
              code: resLogin.code
            },
            method: "post",
            success: function (resSession) {
              // console.log(resSession);
              if (resSession.data.code === 200) {//登陆成功
                app.globalData.openid = resSession.data.openid
                // 获取微信步数，判断步数是否大于2000
                that.getstep()
              } else {
                console.log(resSession);
                wx.showToast({
                  title: resSession.data.msg,
                  icon: 'none',
                  duration: 2000
                })
              }
            },
            fail(res) {
              console.log(res);
            }
          })
        }
      }
    })
  },
  // 活动须知
  getnotice(){
    let that=this
    let host = app.globalData.host
    wx.request({
      url: host +'/H5/base/getConfig',
      success(res){
        // console.log(res.data.data);
        if(res.data.code==="200"){
          that.setData({
            // activity_notice: res.data.data.activity_notice,
            activity_city: res.data.data.activity_city
          })
        }
      },
      fail(res){
        console.log(res);
      }
    })
  },
  //获取用户信息 
  getUserInfo(e) {
    let that = this;
    // console.log(e)
    this.onHide()
    // 获取用户信息
    wx.getSetting({
      success(res) {
        // console.log("res", res)
        if (res.authSetting['scope.userInfo']) {
          console.log("已授权=====")
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success(res) {
              console.log("获取用户信息成功")
              that.setData({
                nick_name: res.userInfo.nickName,
                head_img: res.userInfo.avatarUrl
              })
              that.onLogin()
            },
            fail(res) {
              console.log("获取用户信息失败", res)
            }
          })
        } else {
          console.log("未授权=====")
          that.showSettingToast("请授权")
        }
      }
    })
  },
  // 定位获取位置
  getLocation() {
    var that = this
    wx.getLocation({//调用API得到经纬度
      type: 'wgs84',
      success: function (res) {
        var speed = res.speed
        var accuracy = res.accuracy
        var latitude = res.latitude
        var longitude = res.longitude

        that.setData({
          latitude: res.latitude,
          longitude: res.longitude
        })
        //地址解析
        var demo = new QQMapWX({
          key: '6FGBZ-6HEWU-WZ6V7-2UOBS-L7ZAV-PZBA5'// 这个KEY的获取方式在上面链接 腾讯位置服务的开发文档中有详细的申请密钥步骤
        });
        demo.reverseGeocoder({//地址解析
          location: {
            latitude: latitude,
            longitude: longitude
          },
          success: function (res) {
            // console.log(res.result.address_component);
            that.setData({
              province: res.result.address_component.province,
              city: res.result.address_component.city
            })
            // console.log(that.data.province);
            // console.log(res.result.address_component);
            //获得地址
            that.setData({
              address: res.result.address
            })
          },
          fail: function (res) {
            console.log(res);
          },
          complete: function (res) {
            // console.log(res);
          }
        });
      }
    })
  },
  //获取微信步数判断是否大于2000
  getstep(){
    let that=this
    let host=app.globalData.host
    wx.getWeRunData({
      success(resRun) {
        // console.info(resRun);
        // console.log(resRun.encryptedData);
        //解密的数据；
        wx.request({
          url: host + '/H5/user/getWeRunData',
          data: {
            openid: app.globalData.openid,
            encrypted_data: resRun.encryptedData,
            iv: resRun.iv
          },
          method: 'post',
          success: function (resDecrypt) {
            // console.log(resDecrypt);
            if(resDecrypt.data.code==="200"){
              let steps = resDecrypt.data.data.stepInfoList
              app.globalData.step = steps[steps.length - 1].step
              if (steps[steps.length-1].step>2000){
                // 大于2000，跳转到punch页面
                wx.navigateTo({
                  url: '/pages/punch/punch'
                })
              }else{
                wx.showToast({
                  title: '您今日步数还不足2000，请继续努力',
                  icon:'none',
                  duration:2000
                })
              }
            }
          }
        })
      }
    })
  },
  onLoad: function () {
    this.getLocation()//定位获取地址
    this.getnotice()//活动须知
  }
})
